<template>
  <Dialog v-model="dialogVisible" :title="title" width="80%" :minHeight="900">
    <ExcelParser
      :tips="tips"
      ref="excelParserRef"
      :importApi="DeviceApi.importDevice"
      :targetTableColumns="importColumns"
      :templateName="title"
    />
    <template #footer>
      <el-button type="primary" @click="onBatchImport()" :loading="importLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts" name="ImportDeviceDialog">
import { useValidator } from '@/hooks/web/useValidator'
const { required } = useValidator()
import * as DeviceApi from '@/api/system/device'
import { DICT_TYPE, getDictValuesStr, getIntDictOptions } from '@/utils/dict'
import { ITargetTableColumbnItem } from '@/components/ExcelParser/src/type'

const importLoading = ref(false)
const excelParserRef = ref()

const title = ref('导入设备')
const dialogVisible = ref(false)
const tips = ref([
  '状态: ' + getDictValuesStr(DICT_TYPE.COMMON_STATUS),
  '设备类型: ' + getDictValuesStr(DICT_TYPE.SYSTEM_DEVICE_TYPE)
])

const importColumns = ref<ITargetTableColumbnItem[]>([
  {
    label: '租户名',
    field: 'tenantName',
    rules: [required('租户名不能为空')]
  },
  {
    label: '设备名称',
    field: 'name',
    rules: [required('设备名称不能为空')]
  },
  {
    label: '设备类型',
    field: 'type',
    rules: [required('设备类型不能为空')],
    parseRule: {
      dictType: DICT_TYPE.SYSTEM_DEVICE_TYPE,
      defaultValue: getIntDictOptions(DICT_TYPE.SYSTEM_DEVICE_TYPE)[0].value
    }
  },
  {
    label: 'mac',
    field: 'mac',
    rules: [required('mac不能为空')]
  },
  {
    label: 'sn',
    field: 'sn',
    rules: []
  },
  {
    label: 'imei',
    field: 'imei',
    rules: []
  },
  {
    label: '备注',
    field: 'remark',
    rules: []
  },
  {
    label: '状态',
    field: 'status',
    rules: [required('状态不能为空')],
    parseRule: {
      dictType: DICT_TYPE.COMMON_STATUS,
      defaultValue: getIntDictOptions(DICT_TYPE.COMMON_STATUS)[0].value
    }
  }
])

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

const onBatchImport = async () => {
  importLoading.value = true
  const isSuccess = await excelParserRef.value.onSubmit()
  if (isSuccess) {
    importLoading.value = false
    ElMessage({
      message: '导入成功',
      type: 'success',
      duration: 1000,
      onClose: () => {
        dialogVisible.value = false
      }
    })
    emit('success')
  } else {
    importLoading.value = false
    return
  }
  importLoading.value = false
  dialogVisible.value = false
}

/** 打开弹窗 */
const open = async () => {
  dialogVisible.value = true
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
</script>
